home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 11690 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: mac007016.shef.ac.uk!user
  2. From: m.b.greenwood@sheffield.ac.uk (Mike Greenwood)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Please help me
  5. Date: Tue, 26 Mar 1996 11:47:33 +0000
  6. Organization: University of Sheffield
  7. Message-ID: <m.b.greenwood-2603961147330001@mac007016.shef.ac.uk>
  8. References: <4j6nrl$lfk@badger.wmin.ac.uk>
  9. NNTP-Posting-Host: mac007016.shef.ac.uk
  10.  
  11. In article <4j6nrl$lfk@badger.wmin.ac.uk>, darec@westminster.ac.uk
  12. (Nadarajah Thavaneethan) wrote:
  13.  
  14. > #define  SIZE 60
  15.  
  16. > void main(void)
  17. > {
  18. >         char c[SIZE];
  19. > int index, next;
  20. etc
  21. >                compchar(c[next-1],c[next]);
  22.  
  23. >             printf("\n the line is now %s\n",c);
  24. >  }
  25. >  void compchar (char c1, char c2)
  26. >  {
  27. >  char p;
  28. >           if (c1 > c2)
  29. >               p = c1;
  30. >               c1 = c2;
  31. >               c2 = p;
  32. >  }
  33.  
  34. > This program reads a line of data and sorts it into ascending ASCII sequence
  35. >  it doesn't but it should.
  36.  
  37. Hi there,
  38.  
  39. I think this is quite a simple problem. When you call the function
  40. compchar, and swap if necessary, only a copy of c1 and c2 is sent to the
  41. function. This means that c[next-1] and c[next] in the main() function
  42. don't get swapped even if c1 and c2 do. One way to avoid this is to
  43. declare c[SIZE] as global, i.e. before main(), and call 'void
  44. compchar(void)'.
  45. Inside the compchar() function you could then operate with:
  46.    if (c[next-1] > c[next])
  47.       etc...
  48.  
  49. Another way around this is to use pointers, because pointers point to the
  50. real values whatever, and a copy of a pointer still points to the real
  51. variable. This is the better way, but requires a heavier modificaton to
  52. your program.
  53.  
  54. By the way, if you want to avoid nasty responses, declare:
  55.    int main()
  56.    ...
  57.    return (0);
  58.  
  59. rather than 
  60.    void main(void)
  61.  
  62. the latter is not standard despite what certain books may say. I used to
  63. do it but have seen the error of my ways thanks to this newsgroup.
  64.  
  65. Hope this helps.
  66.  
  67. Cheers
  68. Mike Greenwood
  69.